﻿using ADODB;
using fuzhu;
using LH.Model.PU;
using LH.Model.ST;
using Newtonsoft.Json;
using SqlSuarEntity;
using SqlSugar;
using System.Data;
using System.Security.Cryptography;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.AS;
using XXX.Models.XXXEntities;
using ZDEntity;
using static XXX.Models.WMS.ScanBarcode;

namespace Yonyou.U8.BO
{

    public class RdRecord01VM : ST_Rdrecord01
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        //是否wms使用
        public bool bWMS { get; set; }
        public string xmlConfig { get; set; }
        public string cDatabase = "";

        public RdRecord01VM(Head head, List<Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }

      

        public  RetModel2 AddVerify()
        {


            string idcheck = "";
            if (Exists(ref idcheck))
            {
                return DBService.ReErrObject($"当前单据号{this.head.ccode}已存在");
            }
            foreach (Body body in bodies)
            {
                body.editprop = "A";
            }

            string cRe = GetAddInfo();
            if (cRe != "ok")
            {
                return DBService.ReErrObject("获取基础信息失败:" + cRe);
            }


            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            });
            InventoryVM inventoryVM = new InventoryVM();
            HashSet<string> uniqueCinvCodes = new HashSet<string>();
            foreach (Body body in bodies)
            {
                body.editprop = "A"; // 设置 editprop 属性
                if (!string.IsNullOrEmpty(body.cinvcode))
                {
                    uniqueCinvCodes.Add(body.cinvcode);
                }
            }
            try
            {
                 
                // Step 1: 收集所有唯一的 cinvcode 
                inventoryVM.HandlerTopQty(db, uniqueCinvCodes);

                if (!Rdrecord01DALCO.AddVerifyRdrecord01(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    //审核失败后，检查是否有采购入库单生成，如果有，则删除
                    string cerr2 = "";
                    if (!string.IsNullOrEmpty(id))
                    {
                        Rdrecord01DALCO.VerifyRdrecord01(id, xmlConfig, "delete", out cerr2);
                    }

                    throw new Exception("新增失败：" + err);
                }

                else
                {
                     
                        DateTime dDate = DbHelper.GetDbDate(head.ddate);
                        int iid = DbHelper.GetDbInt(id);
                     
                    db.Updateable<RdRecord01>()
                  .SetColumns(u => new RdRecord01()
                  {
                      dVeriDate = dDate,
                      cHandler = head.cmaker
                  })
                  .Where(u => u.ID == iid)
                  .ExecuteCommand();
                    ////不是wms的情况，检查单据号是不是传入的单据号（单据编码选项是 相同的就自动生成）。 如果不是，删除
                    //if (!bWMS)
                    //{

                    //    if (ccode != head.ccode && head.ccode != WMSPara.rd01Code)
                    //    {
                    //        //单据编码选项判断
                    //        string sql = string.Format(@"Select  bRepeatReDo  From VoucherNumber Where CardNumber='24'");
                    //        int iRepeat = DbHelper.GetDbInt(db.Ado.GetScalar(sql));
                    //        if (iRepeat == 1)
                    //        {
                    //            string cerr2 = "";
                    //            Rdrecord01DALCO.VerifyRdrecord01(id, xmlConfig, "unverify,delete", out cerr2);
                    //            throw new Exception("单据已生成，重复");
                    //        }
                    //    }
                    //}
                    //else
                    //{
                    //    //wms的情况，因为保存是无单据号，根据传入的parentid进行判断。默认字段使用扩展自定义项10
                    //    string cParentid = head.cdefine10;
                    //    if (!string.IsNullOrEmpty(cParentid))
                    //    {
                    //        //检查cParentid 是否存在
                    //        string sqlcx = string.Format(@"select count(*) sl from rdrecord01 a  where  a.cdefine10='{0}' and a.id <>'{1}'", cParentid, id);
                    //        int icntUniq = DbHelper.GetDbInt(db.Ado.GetScalar(sqlcx));
                    //        if (icntUniq > 0)
                    //        {
                    //            Rdrecord01DALCO.VerifyRdrecord01(id, xmlConfig, "unverify,delete", out _);
                    //            throw new Exception("之前单据已生成，重复");
                    //        }
                    //    }

                    //}



                }
                //生成的id赋值
                head.id = id;
                
                inventoryVM.UnHandlerTopQty(db, uniqueCinvCodes);
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                inventoryVM.UnHandlerTopQty(db, uniqueCinvCodes);
                return DBService.ReErrObject(ex.Message);
            }



        }
 

        public string GetAddInfo()
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                   for (int i = 0; i < bodies.Count; i++)
                     {
                        string cInvCode = bodies[i].cinvcode;
                        WMS_GetSource source = new WMS_GetSource();
                        if (head.csource == "采购到货单")
                        {
                            
                              int iArrsId =DbHelper.GetDbInt(bodies[i].iarrsid);
                                source = db.Queryable<PU_ArrivalVouchs>()
                                .InnerJoin<PU_ArrivalVouch>((a, b) => a.ID == b.ID && a.Autoid == iArrsId) 
                                .Select((a, b) => new WMS_GetSource
                                {
                                    cPTCode = b.cPTCode,
                                    cVenCode= b.cVenCode,
                                    iExchRate = b.iExchRate,
                                    cCode =b.cCode,
                                    cDepCode =b.cDepCode,
                                    cPersonCode=b.cPersonCode,
                                    cPOCode = b.cpocode,
                                    cexch_name = b.cexch_name,
                                    cBusType = b.cBusType,
                                    iTaxRate  = a.iTaxRate,
                                    dDate= b.dDate,
                                    cInvCode = a.cInvCode,
                                    cUnitID = a.cUnitID,
                                    cMemo = b.cMemo,
                                    cbMemo =a.cbMemo,
                                    bTaxCost = a.bTaxCost,
                                    iOriTaxCost = a.iOriTaxCost,  
                                    iPOsID = a.iPOsID,
                                    iChangeRate = a.iinvexchrate,
                                    cItem_class = a.cItem_class,
                                    cItemCode = a.cItemCode,
                                    cItemName = a.cItemName ,
                                    cBatchProperty6  =a.cBatchProperty6,
                                    cBatchProperty7 = a.cBatchProperty7
                                }).First();
                            if (source == null )
                            {
                                return string.Format("第{0}行到货单ID不正确，查询不到到货单", (i + 1).ToString());
                            } 
                        }
                        else if (head.csource == "采购订单")
                        {
                            int iPosId = DbHelper.GetDbInt(bodies[i].iposid);
                            source = db.Queryable<PO_Podetails>()
                            .InnerJoin<PO_Pomain>((a, b) => a.POID == b.POID && a.ID == iPosId)
                            .Select((a, b) => new WMS_GetSource
                            {
                                cPTCode = b.cPTCode,
                                cVenCode = b.cVenCode,
                                iExchRate = b.nflat,
                                cCode = b.cPOID,
                                cDepCode = b.cDepCode,
                                cPersonCode = b.cPersonCode,
                                cPOCode = "",
                                cexch_name = b.cexch_name,
                                cBusType = b.cBusType,
                                iTaxRate = a.iPerTaxRate,
                                dDate = b.dPODate,
                                cInvCode = a.cInvCode,
                                cUnitID = a.cUnitID,
                                cMemo = b.cMemo,
                                cbMemo = a.cbMemo,
                                bTaxCost = a.bTaxCost,
                                iOriTaxCost = a.iTaxPrice,
                                iPosid = a.ID,
                            }).First();
                            if (source == null)
                            {
                                return string.Format("第{0}行到货单ID不正确，查询不到到货单", (i + 1).ToString());
                            }
                        }
                        else
                        {
                            //没有处理来料检验单
                            return "无来源单据，无需处理";
                        
                        }
                        if (i == 0 && source!=null)
                        {
                            head.cptcode = source.cPTCode;
                            head.cvencode = source.cVenCode;
                            head.cdepcode = source.cDepCode;
                            head.cpersoncode = source.cPersonCode;
                            head.cordercode = source.cPOCode;
                         
                            head.cexch_name = source.cexch_name;
                            head.itaxrate = DbHelper.GetDbString(source.iTaxRate);
                            head.iexchrate = DbHelper.GetDbString(source.iExchRate);
                            head.cbustype = source.cBusType;

                            if (head.csource=="采购到货单")
                            {
                                head.carvcode = source.cCode;
                                head.darvdate = source.dDate.ToString("yyyy-MM-dd");
                                if (head.cbustype == "委外加工")
                                {
                                    head.csource = head.csource.Replace("采购", "委外");
                                }
                            }
                           
                            
                            //rdrecord01.head.cchkcode = DbHelper.GetDbString(dt.Rows[0]["CCHECKCODE"]);

                        }

                        if (WMSPara.CheckInv01 == "Y" && source.cInvCode != bodies[i].cinvcode)
                        {
                            return string.Format("第{0}行订单物料和{1}不一致", (i + 1).ToString(), cInvCode);
                        }


                        //项目大类名称，这个值的空的，需要重新取数

                        //bodies[i].citemcname = source.cItemCName;
                        bodies[i].citemcode = source.cItemCode;
                        bodies[i].citem_class = source.cItem_class;
                        bodies[i].cname = source.cItemName;
                        //没有检查自由项,是否和来源订单一样


                        bodies[i].cinvcode = source.cInvCode;
                                bodies[i].btaxcost =DbHelper.GetDbString(source.bTaxCost);
                                bodies[i].itaxrate = DbHelper.GetDbString(source.iTaxRate);
                               bodies[i].ioritaxcost = DbHelper.GetDbString(source.iOriTaxCost);         
                                //写其他金额
                                decimal dSum = Math.Round(DbHelper.GetDbdecimal(bodies[i].ioritaxcost) * DbHelper.GetDbdecimal(bodies[i].iquantity), 2);
                                decimal dMoney = Math.Round(dSum / (1 + DbHelper.GetDbdecimal(bodies[i].itaxrate) / 100), 2);
                                decimal dTax = dSum - dMoney;
                                decimal ioricost = dMoney / DbHelper.GetDbdecimal(bodies[i].iquantity);
                                decimal dExch = DbHelper.GetDbdecimal(head.iexchrate);

                                bodies[i].iorisum = dSum.ToString("0.00");
                                bodies[i].iorimoney = dMoney.ToString("0.00");
                                bodies[i].ioritaxprice = (dSum - dMoney).ToString("0.00");
                                bodies[i].iprice = (dMoney * dExch).ToString("0.00");
                                bodies[i].iaprice = (dMoney * dExch).ToString("0.00");
                                bodies[i].facost = (ioricost * dExch).ToString("0.000000");

                                bodies[i].isum = (dSum * dExch).ToString("0.00");
                                //bodies[i].imoney = (dMoney * dExch).ToString("0.00");  //累计结算金额，不能写
                                bodies[i].itaxprice = ((dSum - dMoney) * dExch).ToString("0.00");
                                bodies[i].ioricost = ioricost.ToString("0.000.000000");

                                bodies[i].iunitcost = (ioricost * dExch).ToString("0.000000");
                          

                                if (head.cbustype == "普通采购")
                                {
                                    bodies[i].iposid = DbHelper.GetDbString(source.iPOsID);
                                }
                                else
                                {

                                    bodies[i].iomodid = DbHelper.GetDbString(source.iPOsID);
                                }
                                //采购到货单，不需要赋值，因为已经写入
                                //bodies[i].iarrsid = DbHelper.GetDbString(source.Autoid);
                           
                                //rdrecord01.bodies[i].ccheckcode = DbHelper.GetDbString(dt.Rows[0]["CCHECKCODE"]);
                                //rdrecord01.bodies[i].ccheckpersoncode = DbHelper.GetDbString(dt.Rows[0]["CCHECKPERSONCODE"]);
                                //bodies[i].dcheckdate = DbHelper.GetDbString(dt.Rows[0]["autoid"]);
                                bodies[i].cpoid = source.cPOCode;
                                if(head.csource=="采购到货单")
                                {
                                    bodies[i].cbarvcode = source.cCode;
                                    bodies[i].dbarvdate = source.dDate.ToString("yyyy-MM-dd");
                                }
                                  
                                bodies[i].cassunit = source.cUnitID;

                        //
                            InvProperty invProperty = new InventoryVM().GetInvProperty(cInvCode, bodies[i].dmadedate, bodies[i].dvdate);
                            if (invProperty==null)
                            {
                                return string.Format("第{0}行订单物料和{1}不存在", (i + 1).ToString(), cInvCode);
                            }
                            //iGroupType=0,无换算率，1,固定换算率，2,浮动换算率
                            if (invProperty.iGroupType!="0")
                            {
                                //辅助计量单位来源于来源单据，如果没有取库存单位
                                if (string.IsNullOrEmpty(bodies[i].cassunit))
                                {
                                    bodies[i].cassunit = invProperty.cSTComUnitCode;
                                }
                                 if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(source.iChangeRate)))
                                    {
                                    bodies[i].iinvexchrate = invProperty.iChangRate;
                                }
                                else
                                {
                                    bodies[i].iinvexchrate = DbHelper.GetDbString(source.iChangeRate);
                                }
                                bodies[i].inum = (DbHelper.GetDbdecimal(bodies[i].iquantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate)).ToString("0.000000");
                            }

                            //是否批次管理
                            if (!invProperty.bInvBatch)
                            {
                                bodies[i].cbatch = "";
                            }
                            else if (string.IsNullOrEmpty(bodies[i].cbatch))
                            {
                                return string.Format("第{0}行订单物料{1}有批次管理，未录入批次", (i + 1).ToString(), cInvCode);
                            }
                            else
                        {
                            bodies[i].cbatchproperty6 = source.cBatchProperty6;
                            bodies[i].cbatchproperty7 = source.cBatchProperty7;


                        }
                            //自由项，未处理
                         
                        //有效期管理,根据生产日期或者失效日期推算 
                           if(invProperty.bInvQuality)
                          {
                             if (string.IsNullOrEmpty(bodies[i].dmadedate) && string.IsNullOrEmpty(bodies[i].dvdate))
                            {
                                return string.Format("第{0}行订单物料生产日期或者失效日期未录入", (i + 1).ToString());
                            }
                             else
                            {
                                bodies[i].dvdate =DbHelper.GetDbDate(invProperty.dVDate).ToString("yyyy-MM-dd");
                                bodies[i].imassdate =DbHelper.GetDbString(invProperty.iMassDate);
                                bodies[i].cmassunit = DbHelper.GetDbString(invProperty.cMassUnit);
                                bodies[i].dexpirationdate = DbHelper.GetDbDate(invProperty.dExpeireDate).ToString("yyyy-MM-dd"); ;
                                bodies[i].iexpiratdatecalcu = DbHelper.GetDbString(invProperty.iexpiratdatecalcu);
                            }
                            

                        }


                    }
                     
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
           
                
               
            
            
            return "ok";
        }

        /// <summary>
        /// 参照采购订单的实体
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public RdRecord01VM GetAddEntity_FromPO(API_Rdrecord obj, ref string cErr)
        {

            try
            {
                ST_Rdrecord01.Head head = new ST_Rdrecord01.Head
                {
                    bWireless = "1",
                    cvouchtype = "01",
                    cbustype = "普通采购",
                    csource = "采购订单",
                    ccode = obj.cCode,
                    cwhcode = obj.cWhCode,
                    //cdefine1 = obj.cCode,
                    ddate = DbHelper.GetDbDate(obj.dDate).ToString("yyyy-MM-dd"),
                    cpersoncode = obj.cPersonCode,
                    cdepcode = obj.cDepCode,
                    cmaker = obj.cMaker,
                    cvencode = obj.cVenCode,
                    dveridate = DbHelper.GetDbDate(obj.dDate).ToString("yyyy-MM-dd"),
                    chandler = obj.cHandler,
                    cmemo = obj.cMemo,
                    crdcode = obj.cRdCode,
                    iswfcontrolled = "0",
                    vt_id = "27",
                   idiscounttaxtype = "0",
                    bredvouch = "0",
                    brdflag = "1",
                   iPrintCount = "0",
                    cdefine1 = obj.cDefine1,
                    cdefine2 = obj.cDefine2,
                    cdefine3 = obj.cDefine3,
                    cdefine4 = obj.cDefine4,
                    cdefine5 = obj.cDefine5,
                    cdefine6 = obj.cDefine6,
                    cdefine7 = obj.cDefine7,
                    cdefine8 = obj.cDefine8,
                    cdefine9 = obj.cDefine9,
                    cdefine10 = obj.cDefine10,
                    cdefine11 = obj.cDefine11,
                    cdefine12 = obj.cDefine12,
                    cdefine13 = obj.cDefine13,
                    cdefine14 = obj.cDefine14,
                    cdefine15 = obj.cDefine15,
                    cdefine16 = obj.cDefine16,
                };
                

                List<LH.Model.ST.ST_Rdrecord01.Body> bodies = new List<LH.Model.ST.ST_Rdrecord01.Body>();
                if (obj.itemList != null && obj.itemList.Count > 0)
                {
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {


                        int i = 0;
                        foreach (var item in obj.itemList)
                        {
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.iQuantity)))
                            {
                                throw new Exception("数量不能为空");
                            }
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.cInvCode)))
                            {
                                throw new Exception("存货编码不能为空");
                            }

                            i++;
                            ST_Rdrecord01.Body body = new ST_Rdrecord01.Body
                            {

                                cinvcode = item.cInvCode,
                                cfree1 = item.cFree1,
                                cfree2 = item.cFree2,
                                cfree3 = item.cFree3,
                                cfree4 = item.cFree4,
                                irowno = i.ToString(),
                                iquantity = DbHelper.GetDbString(item.iQuantity),
                                cbatch = item.cBatch,
                                cposition = item.cPosCode,
                                inum = DbHelper.GetDbString(item.iNum),
                                cbmemo = item.cBMemo,
                                citemcode = item.cItemCode,
                                citemcname = item.cItem_Name,
                                citem_class = item.cItem_Class,


                                //33自定义项作为mes行id
                                cdefine31 = item.cRowId,

                                //从22 写到37
                                cdefine22 = item.cDefine22,
                                cdefine23 = item.cDefine23,
                                cdefine24 = item.cDefine24,
                                cdefine25 = item.cDefine25,
                                cdefine26 = item.cDefine26,
                                cdefine27 = item.cDefine27,
                                cdefine28 = item.cDefine28,
                                cdefine29 = item.cDefine29,
                                cdefine30 = item.cDefine30,
                                cdefine33 = item.cDefine33,
                                cdefine32 = item.cDefine32,

                                cdefine34 = item.cDefine34,
                                cdefine35 = item.cDefine35,
                                cdefine36 = item.cDefine36,
                                cdefine37 = item.cDefine37

                            };

                            //采购入库单关联处理
                            if (!string.IsNullOrEmpty(item.cSoureRowId))
                            {
                                if (head.csource == "采购到货单")
                                { 
                                    var row = db.Queryable<PU_ArrivalVouchs>().Where(x => x.cDefine31 == item.cSoureRowId).First();
                                    if (row == null)
                                    {
                                        throw new Exception($"{obj.cCode}物料{item.cInvCode},来源行ID{item.cSoureRowId}无法关联到到货单");
                                    }
                                    else
                                    {
                                        body.iarrsid = row.Autoid.ToString(); 
                                    }
                                }
                                else if (head.csource == "采购订单")
                                {
                                    var row = db.Queryable<PO_Podetails>().Where(x => x.cDefine31 == item.cSoureRowId).First();
                                    if (row == null)
                                    {
                                        throw new Exception($"{obj.cCode}物料{item.cInvCode},来源行ID{item.cSoureRowId}无法关联到采购订单");
                                    }
                                    else
                                    {
                                        body.iposid = row.ID.ToString();
                                    }
                                }
                                
                            }
                            else
                            {
                                throw new Exception("来源行id为空，无法关联采购订单");
                            }

                           
                            bodies.Add(body);
                        }
                    }
                }
                 


                RdRecord01VM model = new RdRecord01VM(head, bodies);
                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            } 

        }

        /// <summary>
        /// 传入json转换成PurchaseOrderVM
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public RdRecord01VM GetCodeEntity(API_Rdrecord obj, ref string cErr)
        {

            try
            {

                ST_Rdrecord01.Head head = new ST_Rdrecord01.Head();
                head.ccode = obj.cCode;
                List<ST_Rdrecord01.Body> bodies = new List<ST_Rdrecord01.Body>();

                RdRecord01VM model = new RdRecord01VM(head, bodies);

                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }





        }


        /// <summary>
        /// 采购入库单 弃审并删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 UnverifyDelete()
        {
            try
            {
                string ID = "";
                if (!Exists(ref ID))
                {
                    return DBService.ReOKObject("当前单据号已删除");
                }
                else
                {
                    head.id = ID;
                }
                if (!Rdrecord01DALCO.VerifyRdrecord01(ID, xmlConfig, "unverify,delete", out string err))
                {
                    return DBService.ReErrObject("弃审失败：" + err);
                }

                return DBService.ReOKObject(head.ccode + "删除完成");
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }
        /// <summary>
        /// 检查单号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select ID from RdRecord01 where ccode='{0}' ", head.ccode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));
                
                 
                if (id == null)
                {
                    return false;
                }
                else
                {
                    head.id = id;
                    return true;
                }
    
            } 
        
        }

        
    }
}
